package android.serialport.api;

import android.util.Log;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort 
{
	private static final String TAG = "SerialPort";

	private FileDescriptor mFd;
	private FileInputStream mFileInputStream;
	private FileOutputStream mFileOutputStream;

	/**
	 *
	 * @param device 串口节点
	 * @param baudRate 波特率
	 */
	public SerialPort(String path, int baudRate)
	{
		mFd = open(path, baudRate, 0);

		if (mFd == null)
		{
			Log.e(TAG, "native open returns null");
			return;
		}
		mFileInputStream = new FileInputStream(mFd);
		mFileOutputStream = new FileOutputStream(mFd);
	}

	/**
	 * 是否存在该串口节点，如果不存在，则无法正常进行读写
	 *
	 * @return
	 */
	public boolean isSupport(){
		return mFd != null;
	}

	public InputStream getInputStream()
	{
		return mFileInputStream;
	}

	public OutputStream getOutputStream()
	{
		return mFileOutputStream;
	}

	/**
	 * 关闭串口
	 */
	public void close(){
		if (mFd != null){
			close(mFd);
		}
		mFd = null;
	}

	private native FileDescriptor open(String path, int baudRate, int flags);

	private native void close(FileDescriptor fd);
	
	static{
		System.loadLibrary("SerialPort");
	}
}
